package com.example.cmpe277stockdata;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import com.example.cmpe277stockdata.LandingActivity.RealTimeData;
import com.example.cmpe277stockdata.RSSFeeds.RealTimeRSSFeed;
import com.example.cmpe277stockdata.RSSFeeds.ResultClass;
import com.example.cmpe277stockdata.beans.RealTimeBean;
import com.example.cmpe277stockdata.beans.UserBean;
import com.example.cmpe277stockdata.beans.UserPortfolio;
import com.example.cmpe277stockdata.constants.DataConstants;
import com.example.cmpe277stockdata.dataaccess.AzureLogin;
import com.example.cmpe277stockdata.dataaccess.AzurePortfolio;
import com.example.cmpe277stockdata.dataaccess.PortFolioDB;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.TableQueryCallback;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.ListView;

public class PortfolioActivity extends Activity {

	private Context ctx;
	private ListView listviewRealTime;
	public ArrayList<RealTimeBean> realTimeData;
	private UserBean userData = null;
	private List<UserPortfolio> userSelection;
	AzurePortfolio portfolioazure;
	private MobileServiceClient mClient;
	List<UserPortfolio> result = new ArrayList<UserPortfolio>();;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_portfolio);
		
		ctx=this;
		try {
			portfolioazure = new AzurePortfolio(getApplicationContext());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		userData = (UserBean) getIntent().getSerializableExtra(DataConstants.USER_DATA);
	}

	public List<UserPortfolio> getPortFolioList(int userId)
	{
		
		try {
			mClient = new MobileServiceClient(
					"https://stockdata.azure-mobile.net/",
					"gbRGSggWlHFQwsQmeMgEULUirbGHgk27", ctx);
		
		MobileServiceTable<UserPortfolio> table = mClient.getTable("UserPortfolio", UserPortfolio.class);
		table.where().field("userId").eq(String.valueOf(userId)).execute(new TableQueryCallback<UserPortfolio>() {

			@Override
			public void onCompleted(
					List<UserPortfolio> checkeduser,
					int arg1,
					Exception exception,
					ServiceFilterResponse arg3) {
				if (exception == null) {
					if(checkeduser == null || checkeduser.size() < 1)
					{
						DataConstants.IS_AZURE_ACTION_COMPLETE = true;
						userSelection = DataConstants.userSelection;
						
				        RealTimeData realTimeData = new RealTimeData();
				        realTimeData.execute();	
					}
					else
					{
						DataConstants.IS_AZURE_ACTION_COMPLETE = true;
						result = new ArrayList<UserPortfolio>();
						for(UserPortfolio portfolio : checkeduser)
						{
							UserPortfolio data = new UserPortfolio();
							data.setCompanyName(portfolio.getCompanyName());
							data.setTickerSymbol(portfolio.getTickerSymbol());
							data.setUserName(portfolio.getUserName());
							data.setUserId(portfolio.getId());
							data.setTableId(portfolio.getTableId());
							result.add(data);
						}
						
						DataConstants.userSelection = result;
						userSelection = DataConstants.userSelection;
						
				        RealTimeData realTimeData = new RealTimeData();
				        realTimeData.execute();	

					}

				} else {
					DataConstants.IS_AZURE_ACTION_COMPLETE = true;
					userSelection = DataConstants.userSelection;
					
			        RealTimeData realTimeData = new RealTimeData();
			        realTimeData.execute();	
				}


			}
		});

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		try {
			portfolioazure = new AzurePortfolio(getApplicationContext());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		userData = (UserBean) getIntent().getSerializableExtra(DataConstants.USER_DATA);
		getPortFolioList(userData.getId());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.portfolio, menu);
		return true;
	}

	public class RealTimeData extends AsyncTask<String, Void, ArrayList<RealTimeBean>>
    {		
    	
		@Override
		protected void onPostExecute(ArrayList<RealTimeBean> result) 
		{
			realTimeData = result;
						
			listviewRealTime = (ListView) findViewById(R.id.lstPortfolioRealTimeContent);
			
			RealTimeAdapter adapter =  new RealTimeAdapter(ctx, R.layout.real_time_data, realTimeData);
			adapter.setUserData(userData);
			
			listviewRealTime.setAdapter( adapter);
		}

		@Override
		protected ArrayList<RealTimeBean> doInBackground(String... arg0) 
		{
			RealTimeRSSFeed read= new RealTimeRSSFeed();
			ArrayList<RealTimeBean> result = new ArrayList<RealTimeBean>();
			if(userSelection != null)
			{
				for (int i=0;i<userSelection.size();i++)
				{
					try
					{
						RealTimeBean data = new RealTimeBean();
						data = read.getRealTimeRate(userSelection.get(i).getTickerSymbol(),
								userSelection.get(i).getCompanyName());
						result.add(data);
					}
					catch(Exception e)
					{
						System.out.println(e.getMessage());
					}
				}
			}
			return result;
		}
    	
    }
}
